<template>
  <div>
    <el-row :gutter="10" style="margin: 10px 0;">
      <!-- 遍历商品大类数据，每行显示两个饼图 -->
      <el-col v-for="(bigType, index) in bigTypeList" :key="index" :span="12" >
        <el-card style="margin-bottom: 20px">
          <!-- 确保id的唯一性，使用index -->
          <div :id="'pie-' + index" style="width: 100%; height: 400px"></div>
        </el-card>
      </el-col>

    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import axios from '@/util/axios'; // 修改为正确的axios路径

export default {
  name: "Charts",
  data() {
    return {
      bigTypeList: [],  // 商品大类数据列表
      bigTypeNames: []  // 商品大类名称列表，用于饼图标题
    };
  },
  mounted() {
    // 从后端获取商品大类及其库存数据
    axios.get('/admin/charts/pie')
        .then(response => {
          const pieData = response.data.data?.pie || [];
          const bigTypeNames = response.data.data?.bigTypeNames || [];

          this.bigTypeList = pieData;
          this.bigTypeNames = bigTypeNames;

          // 使用 this.$nextTick 来确保 DOM 渲染完成后再初始化图表
          this.$nextTick(() => {
            // 渲染每个大类的饼图
            this.bigTypeList.forEach((bigType, index) => {
              this.renderPieChart(bigType, bigTypeNames[index], index);
            });
          });

          console.log("返回的数据:", response);
        })
        .catch(error => {
          console.error("请求数据失败：", error);
        });
  },
  methods: {
    // 渲染每个商品大类的饼图
    renderPieChart(bigType, bigTypeName, index) {
      const pieDom = document.getElementById('pie-' + index);

      if (pieDom) {
        const pieChart = echarts.init(pieDom);

        const option = {
          title: {
            text: `${bigTypeName} 库存统计`,  // 使用大类名称作为标题
            subtext: '库存总和',
            left: 'center'
          },
          tooltip: {
            trigger: 'item'
          },
          legend: {
            orient: 'vertical',
            left: 'left'
          },
          series: [
            {
              name: '库存',
              type: 'pie',
              center: ['50%', '60%'],
              radius: '60%',
              data: bigType.products.map(product => ({
                name: product.name,  // 使用商品名称
                value: product.value  // 使用库存数据
              })),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        };

        pieChart.setOption(option);
      } else {
        console.error(`Pie chart DOM with id 'pie-${index}' not found.`);
      }
    }
  }
};
</script>

<style scoped>
</style>
